package br.com.abril.booking;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import br.com.abril.booking.transformer.BookingMaintenanceTransformer;
import br.com.abril.prevision.ExecutivePrevision;
import br.com.abril.prevision.PrevisionService;
import br.com.abril.wallet.BookingWallet;
import br.com.abril.wallet.PrevisionWallet;

import com.force.abril.api.maintanence.client.BookingMaintenanceClientService;
import com.force.abril.api.maintanence.client.request.MaintenanceEntry;

@Component
public class PrevisionLoader {

	@Autowired
	private PrevisionService previsionService;

	@Autowired
	private BookingMaintenanceTransformer transformer;

	@Autowired
	private BookingMaintenanceClientService service;

	@Transactional(readOnly = true)
	public Page<PrevisionWallet> getWalletByPage(Integer nextPage) { 
		Pageable pageable = new PageRequest(nextPage, PrevisionWallet.PAGE_SIZE);
		return previsionService.allWallets().findAll(pageable); 
	}

	public void processWallets(List<PrevisionWallet> wallets) {

		for (PrevisionWallet wallet : wallets) {

			List<ExecutivePrevision> previsionExecutives = previsionService.getExecutivePrevisionService()
																			.findExecutivesforPrevisionByWallet( wallet.getWallet());
			
			if (previsionExecutives.isEmpty() ) continue;

			processExecutivesFromPrevision(previsionExecutives);

		}

	}



	@Transactional
	public void processExecutivesFromPrevision(List<ExecutivePrevision> executives) {
		List<ExecutivePrevision> lastExecutives = previsionService
														.filterTeamByLastPrevison(executives.get(0).getPrevisao__c()
																				, executives);
		
		MaintenanceEntry request = transformer.toMaintenancePrevision(lastExecutives);
		try{
			service.create(request);
		} catch (Exception e) {
			previsionService.updateExecutivePrevisionsWithError(lastExecutives, e);
		}
	
	
	}

	public void load() {

		// Determinar o tamanho da lista
		int page = 0;
		int totalOfPages = 1;

		while (page <= totalOfPages) {

			Page<PrevisionWallet> walletPage = getWalletByPage(page);

			if (page == 0) {
				totalOfPages = walletPage.getTotalPages();
			}

			processWallets(walletPage.getContent());

			page++;

		}

		//

	}

}
